package com.yifushidai.task;

import com.alibaba.fastjson.JSON;
import com.yifushidai.api.DynamicTempkeyTask;
import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.DynamicTempkey;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.KeypassBandEntityMapper;
import com.yifushidai.mapper.OptDeviceLogMapper;
import com.yifushidai.service.DynamicTempkeyService;
import com.yifushidai.service.IcBindService;
import com.yifushidai.service.SfzUploadService;
import com.yifushidai.utils.CustomPackUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class ScheduledTasks {
    private Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private KeypassBandEntityMapper keyPassMapper;
    @Autowired
    private OptDeviceLogMapper optDeviceLogMapper;

    @Autowired
    private DynamicTempkeyService dynamicTempkeyService;
    @Autowired
    private SfzUploadService sfzUploadService;
    @Autowired
    private IcBindService icBindService;
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;

    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

//    @Scheduled(fixedRate = 5000) ：上一次开始执行时间点之后5秒再执行
//    @Scheduled(fixedDelay = 5000) ：上一次执行完毕时间点之后5秒再执行
//    @Scheduled(initialDelay=1000, fixedRate=5000) ：第一次延迟1秒后执行，之后按fixedRate的规则每5秒执行一次
//    @Scheduled(cron="*/5 * * * * *") ：通过cron表达式定义规则

    @Scheduled(cron = "0 0 0 * * ?")
    public void initSaveToday() {
        apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().savetoday(0.0).build(), new Example(ApiUniqueMac.class));
        dynamicTempkeyService.deleteByExpire();
//        icBindService.deleteByExpire();

        logger.warn("@Scheduled(cron = \"0 0 0 * * ?\") initSaveToday()");
    }

    @Scheduled(initialDelay = 100, fixedRate = Long.MAX_VALUE)
    public void initNetworkStatus() {
        apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().ls(CustomPackUtils.OFF_LINE).powerStatus(CustomPackUtils.OFF_LINE).build(), new Example(ApiUniqueMac.class));
        logger.warn("@Scheduled(initialDelay = 100, fixedRate = Long.MAX_VALUE) initNetworkStatus()");
    }

    @Scheduled(initialDelay = 600000, fixedRate = Long.MAX_VALUE)
    public void dynamicTempkeyCron() {
        List<DynamicTempkey> list = dynamicTempkeyService.selectAll();
        for (DynamicTempkey r : list) {
            ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(r.getMac()).build());
            if (null == one) continue;

            DynamicTempkeyTask.scheduledFutureConcurrentHashMap.put(r.getMac() + r.getPushIndex() + "A",
                    threadPoolTaskScheduler.schedule(new MyRunnable(optDeviceLogMapper, keyPassMapper, one, r.getTempKey(), r.getExpireDate()), r.getPushDate()));
            // 必须发xxxx，保证用户有效期间未开门，也能超时失效
            DynamicTempkeyTask.scheduledFutureConcurrentHashMap.put(r.getMac() + r.getPushIndex() + "B",
                    threadPoolTaskScheduler.schedule(new MyRunnable(optDeviceLogMapper, keyPassMapper, one, "xxxx", r.getExpireDate()), r.getExpireDate()));
        }
        logger.warn("@Scheduled(initialDelay = 600000, fixedRate = Long.MAX_VALUE) dynamicTempkeyCron() {}", JSON.toJSONString(list));
    }

//    @Scheduled(fixedDelay = 600000)
//    public void fixedDeleteExpire() {
//
//        dynamicTempkeyService.deleteByExpire();
//        icBindService.deleteByExpire();
//        sfzUploadService.deleteByExpire();
//
//        //定时器的执行优先于注入，因此我们不能通过@Resource注入service。 以下不可用，bean为空
////        IdcardService idcardService = (IdcardService) SpringBeanFactoryUtils.getBean("idcardServiceImpl");
////        idcardService.deleteByTime(new Date());
//    }
}